package com.socket.nio.nio.chat.example2.server.handler;

import com.socket.nio.nio.chat.example2.message.ChatRequestMessage;
import com.socket.nio.nio.chat.example2.message.ChatResponseMessage;
import com.socket.nio.nio.chat.example2.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author Hexudong
 * @date 2025/5/18
 */
// 标记可以在多个ChannelPipeline中安全共享的ChannelHandler实现类
@ChannelHandler.Sharable
public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage chatRequestMessage) throws Exception {
    String to = chatRequestMessage.getTo();
    Channel channel = SessionFactory.getSession().getChannel(to);
    if (channel == null) {
      //如果对方不在线
      ctx.writeAndFlush(ChatResponseMessage.builder()
              .success(false)
              .reason("对方用户不存在或则不在线")
          .build());
    } else {
      // 如果对方在线
      channel.writeAndFlush(ChatResponseMessage.builder()
          .from(chatRequestMessage.getFrom())
          .content(chatRequestMessage.getContent())
          .build());
    }

  }
}
